"""
逻辑连贯性专家代理 - 负责检查内容是否逻辑连贯
"""

from typing import Dict, List, Any, Optional
import time
from loguru import logger

from .base_agent import BaseAgent, AgentResult, ReviewItem
from ..utils.data_loader import ProcessingElement


class LogicCoherenceAgent(BaseAgent):
    """逻辑连贯性专家代理"""
    
    def __init__(self, api_client, config: Dict[str, Any]):
        super().__init__(
            name="逻辑连贯性专家",
            agent_type="logic_coherence",
            api_client=api_client,
            config=config
        )
    
    def get_system_prompt(self) -> str:
        """获取系统提示词"""
        return """你是城市更新方案册逻辑连贯性审查专家，负责检查内容的逻辑一致性。

审查重点：
- 前后表述一致性，识别矛盾或不一致
- 论证过程完整性和逻辑链条清晰度
- 数据与结论的匹配关系
- 方案目标与实施措施的对应性
- 时间安排的合理性和可行性
- 资源配置与需求的匹配度

评分标准（总分100分）：
1. 逻辑一致性（30分）：前后表述无矛盾，论述逻辑清晰
2. 内容连贯性（25分）：段落间衔接自然，主题连贯统一
3. 数据关联性（25分）：数据与结论匹配，论证有据可依
4. 结论合理性（20分）：结论符合逻辑，推理过程合理

扣分规则：
- 严重问题（critical）：每项扣5分
- 重要问题（major）：每项扣3分
- 轻微问题（minor）：每项扣1分

输出JSON格式：
{
    "findings": [
        {
            "item_id": "logic_001",
            "category": "逻辑连贯性",
            "severity": "critical/major/minor/info",
            "description": "具体问题描述",
            "suggestion": "改进建议",
            "location": "问题位置",
            "confidence": 0.9,
            "score_impact": 5,
            "check_item": "逻辑一致性"
        }
    ],
    "summary": "整体逻辑连贯性评估摘要",
    "scoring_details": {
        "logic_consistency_score": 30,
        "content_coherence_score": 25,
        "data_correlation_score": 25,
        "conclusion_rationality_score": 20,
        "total_score": 100,
        "deduction_details": "扣分详情说明"
    }
}

严重性等级：critical(严重逻辑错误)、major(重要逻辑问题)、minor(轻微逻辑瑕疵)、info(逻辑优化建议)"""
    
    def process(self, data: Any, context: Dict[str, Any] = None) -> AgentResult:
        """处理数据并返回逻辑连贯性审查结果"""
        start_time = time.time()
        
        if not self.validate_input(data):
            return self.handle_api_error(
                Exception("输入数据无效"), 
                "逻辑连贯性检查"
            )
        
        try:
            # 提取文本内容进行逻辑分析
            text_content = self._extract_text_content(data)
            
            if not text_content:
                return self.create_result(
                    success=True,
                    findings=[],
                    summary="无文本内容需要进行逻辑连贯性检查",
                    confidence=1.0,
                    processing_time=time.time() - start_time
                )
            
            self.log_processing_start(f"逻辑连贯性检查，文本长度: {len(text_content)}")
            
            # 构建检查提示
            prompt = self._build_logic_check_prompt(text_content, context)
            
            # 调用API进行逻辑分析
            response = self.api_client.chat_completion(
                messages=[
                    {"role": "system", "content": self.get_system_prompt()},
                    {"role": "user", "content": prompt}
                ],
                model=self.config.get('text_model', 'Qwen/Qwen2.5-7B-Instruct')
            )
            
            # 解析响应
            review_items = self.parse_llm_response(response)
            
            # 获取location信息
            locations = context.get('locations', '未知位置') if context else '未知位置'
            
            # 生成结果
            processing_time = time.time() - start_time
            findings = self.format_findings(review_items, default_location=locations)
            summary = self.generate_summary(review_items)
            confidence = self.calculate_confidence(review_items)
            
            self.log_processing_end(True, processing_time, len(findings))
            
            return self.create_result(
                success=True,
                findings=findings,
                summary=summary,
                confidence=confidence,
                processing_time=processing_time,
                metadata={
                    "text_length": len(text_content),
                    "logic_checks_performed": len(review_items),
                    "agent_type": self.agent_type
                },
                locations=locations
            )
            
        except Exception as e:
            return self.handle_api_error(e, "逻辑连贯性检查")
    
    def _extract_text_content(self, data: Any) -> str:
        """提取文本内容"""
        text_parts = []
        
        if isinstance(data, list):
            for item in data:
                if isinstance(item, ProcessingElement):
                    if item.source_type == 'text' and item.content:
                        text_parts.append(f"[{item.category}] {item.content}")
                elif isinstance(item, dict):
                    # 处理分组数据
                    if 'elements' in item:
                        # 这是一个分组，处理其中的元素
                        for element in item['elements']:
                            content = element.get('content', '')
                            if content and isinstance(content, str):
                                category = element.get('category', '未分类')
                                text_parts.append(f"[{category}] {content}")
                    else:
                        # 单个元素
                        content = item.get('content', '')
                        if content and isinstance(content, str):
                            category = item.get('category', '未分类')
                            text_parts.append(f"[{category}] {content}")
        elif isinstance(data, ProcessingElement):
            if data.source_type == 'text' and data.content:
                text_parts.append(data.content)
        elif isinstance(data, dict):
            # 处理分组数据
            if 'elements' in data:
                # 这是一个分组，处理其中的元素
                for element in data['elements']:
                    content = element.get('content', '')
                    if content and isinstance(content, str):
                        category = element.get('category', '未分类')
                        text_parts.append(f"[{category}] {content}")
            else:
                # 单个元素
                content = data.get('content', '')
                if content and isinstance(content, str):
                    text_parts.append(content)
        elif isinstance(data, str):
            text_parts.append(data)
        
        return "\n\n".join(text_parts)
    
    def _build_logic_check_prompt(self, text_content: str, context: Dict[str, Any] = None) -> str:
        """构建逻辑检查提示"""
        prompt_parts = [
            "对以下城市更新方案册内容进行逻辑连贯性审查：",
            "",
            "=== 待审查内容 ===",
            text_content[:4000],  # 限制长度避免超出token限制
        ]
        
        if len(text_content) > 4000:
            prompt_parts.append("\n[注：内容已截断，仅显示前4000字符]")
        
        prompt_parts.extend([
            "",
            "=== 审查要求 ===",
            "重点关注以下逻辑连贯性问题：",
            "1. 前后表述一致性，识别矛盾",
            "2. 论证过程完整性和逻辑链条清晰度",
            "3. 数据与结论匹配关系",
            "4. 方案目标与实施措施对应性",
            "5. 时间安排合理性和可行性",
            "6. 资源配置与需求匹配度",
            "",
            "按照系统提示中的JSON格式输出审查结果。"
        ])
        
        if context:
            prompt_parts.extend([
                "",
                "=== 上下文信息 ===",
                f"文档类型: {context.get('document_type', '未知')}",
                f"审查阶段: {context.get('review_stage', '第三阶段')}",
            ])
        
        return "\n".join(prompt_parts)
    
    def _analyze_logical_structure(self, text_content: str) -> List[ReviewItem]:
        """分析逻辑结构（备用方法）"""
        review_items = []
        
        # 简单的逻辑结构分析
        sentences = text_content.split('。')
        
        # 检查是否有明显的逻辑词汇
        logic_indicators = ['因此', '所以', '由于', '因为', '然而', '但是', '虽然', '尽管']
        contradiction_indicators = ['相反', '不过', '然而', '但是']
        
        for i, sentence in enumerate(sentences):
            sentence = sentence.strip()
            if not sentence:
                continue
            
            # 检查逻辑连接词的使用
            for indicator in logic_indicators:
                if indicator in sentence:
                    # 这里可以添加更复杂的逻辑分析
                    pass
            
            # 检查可能的矛盾表述
            for indicator in contradiction_indicators:
                if indicator in sentence and i > 0:
                    prev_sentence = sentences[i-1].strip()
                    if prev_sentence:
                        # 简单的矛盾检测逻辑
                        review_items.append(self.create_review_item(
                            item_id=f"logic_structure_{i}",
                            category="逻辑结构",
                            severity="info",
                            description=f"发现转折表述，请确认前后逻辑一致性：{prev_sentence}。{sentence}",
                            suggestion="请检查前后表述的逻辑关系是否合理"
                        ))
        
        return review_items
    
    def calculate_detailed_score(self, review_items: List[ReviewItem]) -> Dict[str, Any]:
        """计算详细评分"""
        # 初始分数
        scores = {
            "logic_consistency_score": 30,     # 逻辑一致性
            "content_coherence_score": 25,     # 内容连贯性
            "data_correlation_score": 25,      # 数据关联性
            "conclusion_rationality_score": 20 # 结论合理性
        }
        
        deductions = {
            "logic_consistency_score": 0,
            "content_coherence_score": 0,
            "data_correlation_score": 0,
            "conclusion_rationality_score": 0
        }
        
        deduction_details = []
        
        # 根据问题类型和严重性扣分
        for item in review_items:
            severity_deduction = {"critical": 5, "major": 3, "minor": 1}.get(item.severity, 0)
            
            # 根据问题类别分配扣分
            if "一致性" in item.category or "矛盾" in item.category or "逻辑" in item.category:
                deductions["logic_consistency_score"] += severity_deduction
                deduction_details.append(f"逻辑一致性扣{severity_deduction}分: {item.description[:30]}...")
            elif "连贯" in item.category or "衔接" in item.category or "主题" in item.category:
                deductions["content_coherence_score"] += severity_deduction
                deduction_details.append(f"内容连贯性扣{severity_deduction}分: {item.description[:30]}...")
            elif "数据" in item.category or "关联" in item.category or "匹配" in item.category:
                deductions["data_correlation_score"] += severity_deduction
                deduction_details.append(f"数据关联性扣{severity_deduction}分: {item.description[:30]}...")
            elif "结论" in item.category or "推理" in item.category or "合理" in item.category:
                deductions["conclusion_rationality_score"] += severity_deduction
                deduction_details.append(f"结论合理性扣{severity_deduction}分: {item.description[:30]}...")
            else:
                # 默认扣逻辑一致性分
                deductions["logic_consistency_score"] += severity_deduction
                deduction_details.append(f"逻辑问题扣{severity_deduction}分: {item.description[:30]}...")
        
        # 计算最终分数
        final_scores = {}
        for key, base_score in scores.items():
            final_scores[key] = max(0, base_score - deductions[key])
        
        total_score = sum(final_scores.values())
        
        return {
            **final_scores,
            "total_score": total_score,
            "deduction_details": "; ".join(deduction_details) if deduction_details else "无扣分项"
        }